package com.base.cn.platform.os.common.thread;

import com.base.cn.platform.os.common.filter.RequestData;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * 切换线程时上下文内容传递
 *
 * @author s.li
 * @date 2019/05/09
 */
public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor {

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        //获取当前原线程的RequestAttributes的对象传递过去
        ContextAwareCallable contextAwareCallable = new ContextAwareCallable(task, getRequestData());
        return super.submit(contextAwareCallable);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        ContextAwareCallable contextAwareCallable = new ContextAwareCallable(task, getRequestData());
        return super.submitListenable(contextAwareCallable);
    }

    private RequestData getRequestData(){
        RequestData requestData = RequestData.requestDataThreadLocal.get();
        if(requestData  !=null){
            requestData = requestData.clone();
        }
        return requestData;
    }
}
